package library.net
{
	import flash.events.*;
	import flash.net.Socket;
	import flash.utils.Endian;
	
	public dynamic class AMFClient extends Socket {
		
		public static const MODE_REQUEST:String = "request";
		public static const MODE_RESPONSE:String = "response";
		
		private var response:String;
		private var _socket:Socket;
		private var _readable:Boolean;
		
		public function AMFClient(host:String=null, port:uint=0) {
			super(host, port);
			
			this.endian = Endian.BIG_ENDIAN;
			
			if(host&&port){
				connect(host, port);
			}
			this.addEventListener(Event.CONNECT, handleThis);
			this.addEventListener(ProgressEvent.SOCKET_DATA, handleThis);
			
			this.echo = makeService("echo");
			this.sum = makeService("sum");
			this.list = makeService("list");
		}
		
		private function handleThis(e:Event):void
		{
			switch(e.type){
				case Event.CONNECT :
					
					//this.list();
					break;
			}
		}
		
		
		public function listAllServices():Array
		{
			var list:Array = new Array();
			return list;
		}
		
		
		private var makeService:Function = function(fn:String):Function
		{
			return function(...args):*
			{
				if(this.connected){
					
					var name:String = fn;
					var request:Request = new Request(AMFClient.MODE_REQUEST, name, args);
					this.flush();
					this.writeObject(request);
					this.flush();
					
					var response:*;
					//response = this.readObject();
					
					return response;
				} else {
					throw new IOErrorEvent(IOErrorEvent.IO_ERROR);
				}
			}
		}

		
	}
}

class Request {
	public var mode:String;
	public var service:String;
	public var params:Array;
	public function Request(mode:String, service:String, params:Array)
	{
		this.mode = mode;
		this.service = service;
		this.params = params;
	}
}